package com.icast.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.icast.api.ICast;
import com.icast.interlayer.Interlayer;
import com.icast.tools.LogCat;
import com.smit.dvb.DVBServiceInfo;
import com.smit.dvb.DVBTunerInfo;

public class MainActivity extends Activity {

	private static Activity activity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
				WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

		ICast.onCreate(getApplicationContext());
		activity = this;
		setContentView(R.layout.activity_main);

		playerInit();
		channelInit();
		testInit();
	}

	@Override
	protected void onResume() {
		super.onResume();
		ICast.onResume();

		// DVBServiceInfo[] DVBServiceInfo = ICast.getChannels();
		// if (DVBServiceInfo != null && DVBServiceInfo.length > 0) {
		// createChannelList();
		// new Handler().postDelayed(new Runnable() {
		// @Override
		// public void run() {
		// ICast.startPlay();
		// }
		// }, 3000);
		// } else {
		// new Handler().postDelayed(new Runnable() {
		// @Override
		// public void run() {
		// ICast.startFullScan();
		// }
		// }, 3000);
		// }
	}

	@Override
	protected void onPause() {
		super.onPause();
		ICast.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ICast.onDestroy();
	}

	/**************************************** 测试 ****************************************/

	private LinearLayout ctrlBar1;
	private LinearLayout ctrlBar2;
	private static LinearLayout logList;
	private static ScrollView logScroll;

	private void testInit() {
		ctrlBar1 = (LinearLayout) findViewById(R.id.ctrlbar1);
		ctrlBar2 = (LinearLayout) findViewById(R.id.ctrlbar2);
		logList = (LinearLayout) findViewById(R.id.loglist);
		logScroll = (ScrollView) findViewById(R.id.logscroll);
		logScroll.setFocusable(false);

		addTestButton(1, "挂载状态", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				LogCat.log("isbDVBInitOk = " + ICast.isbDVBInitOk());
			}
		});
		addTestButton(1, "CI菜单", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.openSession();
			}
		});
		addTestButton(1, "获取频道", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				DVBServiceInfo[] DVBServiceInfo = ICast.getChannels();
				if (DVBServiceInfo != null && DVBServiceInfo.length > 0) {
					for (int i = 0; i < DVBServiceInfo.length; i++) {
						DVBServiceInfo info = DVBServiceInfo[i];
						LogCat.log(i + "-" + info.serviceName.trim());
						LogCat.log("channelNumber：" + info.channelNumber);
						LogCat.log("frequency：" + info.frequency);
						LogCat.log("symbolRate：" + info.symbolRate);
						LogCat.log("modulation：" + info.modulation);
						LogCat.log("------------------------");
					}
					LogCat.log("频道总数：" + DVBServiceInfo.length);
					createChannelList();
				} else {
					LogCat.log("获取频道列表失败：频道列表为空");
				}
			}
		});
		addTestButton(1, "启动直播", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.startPlay();
			}
		});
		addTestButton(1, "停止直播", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.stopPlay();
			}
		});
		addTestButton(1, "向上换台", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.playUp();
			}
		});
		addTestButton(1, "向下换台", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.playDown();
			}
		});
		// 数字换台EditText
		final EditText channelEdit = new EditText(activity);
		LayoutParams params = new LayoutParams(200, 60);
		params.setMargins(0, -10, 0, 0);
		channelEdit.setLayoutParams(params);
		channelEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
		channelEdit.setSingleLine(true);
		channelEdit.setTextSize(12);
		channelEdit.setText("1");
		ctrlBar2.addView(channelEdit);
		//
		addTestButton(2, "数字换台", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				String channelNum = channelEdit.getText().toString();
				if (channelNum != null && !channelNum.equals("")) {
					ICast.startPlay(Integer.parseInt(channelNum) - 1);
				}
			}
		});
		addTestButton(1, "全频搜台", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.startFullScan();
			}
		});
		addTestButton(1, "自动搜台", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.startAutoScan();
			}
		});
		addManualScan();
		addTestButton(1, "停止搜台", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				ICast.AbortScan();
			}
		});
		addTestButton(1, "手动重启", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				int x = 0;
				Math.floor(3 / x);
			}
		});
	}

	/**
	 * 添加测试按钮
	 */
	private void addTestButton(int flag, String text, OnClickListener listener) {
		Button button = new Button(this);
		LayoutParams params = new LayoutParams(200, 60);
		params.setMargins(0, -10, 0, 0);
		button.setLayoutParams(params);
		button.setText(text);
		button.setTextSize(12);
		button.setOnClickListener(listener);
		if (flag == 1) {
			ctrlBar1.addView(button);
		} else if (flag == 2) {
			ctrlBar2.addView(button);
		}
	}

	/**
	 * 手动搜台Selector
	 */
	private void addManualScan() {
		LinearLayout manualLayout = createSelectorLayout();
		// 频点
		TextView frequencyText = new TextView(this);
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		frequencyText.setLayoutParams(params);
		frequencyText.setTextSize(12);
		frequencyText.setText("频点");
		manualLayout.addView(frequencyText);
		final EditText frequencyEdit = new EditText(this);
		LayoutParams params1 = new LayoutParams(200, 60);
		frequencyEdit.setLayoutParams(params1);
		frequencyEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
		frequencyEdit.setSingleLine(true);
		frequencyEdit.setTextSize(12);
		frequencyEdit.setText("698000");
		manualLayout.addView(frequencyEdit);
		// 符号率
		TextView symbolRateText = new TextView(this);
		LayoutParams params2 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params2.leftMargin = 10;
		symbolRateText.setLayoutParams(params2);
		symbolRateText.setTextSize(12);
		symbolRateText.setText("符号率");
		manualLayout.addView(symbolRateText);
		final EditText symbolRateEdit = new EditText(this);
		LayoutParams params3 = new LayoutParams(200, 60);
		symbolRateEdit.setLayoutParams(params3);
		symbolRateEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
		symbolRateEdit.setSingleLine(true);
		symbolRateEdit.setTextSize(12);
		symbolRateEdit.setText("6875");
		manualLayout.addView(symbolRateEdit);
		// 调制方式
		LinearLayout modulationLayout = createSelectorLayout();
		TextView modulationText = new TextView(this);
		LayoutParams params4 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		modulationText.setLayoutParams(params4);
		modulationText.setTextSize(12);
		modulationText.setText("调制");
		modulationLayout.addView(modulationText);
		modulation = DVBTunerInfo.MODULATION_64QAM;
		addSelectorButton(modulationLayout, "modulation", "16QAM", DVBTunerInfo.MODULATION_16QAM, false);
		addSelectorButton(modulationLayout, "modulation", "32QAM", DVBTunerInfo.MODULATION_32QAM, false);
		addSelectorButton(modulationLayout, "modulation", "64QAM", DVBTunerInfo.MODULATION_64QAM, true);
		addSelectorButton(modulationLayout, "modulation", "128QAM", DVBTunerInfo.MODULATION_128QAM, false);
		addSelectorButton(modulationLayout, "modulation", "256QAM", DVBTunerInfo.MODULATION_256QAM, false);
		// 带宽
		LinearLayout bandWidthLayout = createSelectorLayout();
		TextView bandWidthText = new TextView(this);
		LayoutParams params5 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		bandWidthText.setLayoutParams(params5);
		bandWidthText.setTextSize(12);
		bandWidthText.setText("带宽");
		bandWidthLayout.addView(bandWidthText);
		bandWidth = DVBTunerInfo.BAND_WIDTH_8;
		addSelectorButton(bandWidthLayout, "bandWidth", "bandWidth_6", DVBTunerInfo.BAND_WIDTH_6, false);
		addSelectorButton(bandWidthLayout, "bandWidth", "bandWidth_7", DVBTunerInfo.BAND_WIDTH_7, false);
		addSelectorButton(bandWidthLayout, "bandWidth", "bandWidth_8", DVBTunerInfo.BAND_WIDTH_8, true);
		// tuner类型
		LinearLayout tunerTypeLayout = createSelectorLayout();
		TextView tunerTypeText = new TextView(this);
		LayoutParams params6 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		tunerTypeText.setLayoutParams(params6);
		tunerTypeText.setTextSize(12);
		tunerTypeText.setText("制式");
		tunerTypeLayout.addView(tunerTypeText);
		tunerType = DVBTunerInfo.TUNER_TYPE_DVBC;
		addSelectorButton(tunerTypeLayout, "tunerType", "DTMB", DVBTunerInfo.TUNER_TYPE_DTMB, false);
		addSelectorButton(tunerTypeLayout, "tunerType", "DVBC", DVBTunerInfo.TUNER_TYPE_DVBC, true);
		addSelectorButton(tunerTypeLayout, "tunerType", "DVBT", DVBTunerInfo.TUNER_TYPE_DVBT, false);
		addSelectorButton(tunerTypeLayout, "tunerType", "DVBT2", DVBTunerInfo.TUNER_TYPE_DVBT2, false);
		addSelectorButton(tunerTypeLayout, "tunerType", "DVBS", DVBTunerInfo.TUNER_TYPE_DVBS, false);
		addSelectorButton(tunerTypeLayout, "tunerType", "DVBS2", DVBTunerInfo.TUNER_TYPE_DVBS2, false);
		// 搜台按钮
		addTestButton(2, "手动搜台", new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				DVBTunerInfo dvbTunerInfo = new DVBTunerInfo();
				String frequency = frequencyEdit.getText().toString();
				if (frequency != null && !frequency.equals("")) {
					dvbTunerInfo.frequency = Integer.parseInt(frequency);// 设置搜索的频点
				}
				String symbolRate = symbolRateEdit.getText().toString();
				if (symbolRate != null && !symbolRate.equals("")) {
					dvbTunerInfo.symbolRate = Integer.parseInt(symbolRate);// 设置搜索的符号率
				}
				dvbTunerInfo.modulation = modulation;
				dvbTunerInfo.bandWidth = bandWidth;
				dvbTunerInfo.tunerType = tunerType;
				// dvbTunerInfo.frequency = 698000;
				// dvbTunerInfo.symbolRate = 6875;
				// dvbTunerInfo.modulation = DVBTunerInfo.MODULATION_64QAM;// 设置搜索的调制方式，DVBTunerInfo中有存储支持的调制方式
				// dvbTunerInfo.bandWidth = DVBTunerInfo.BAND_WIDTH_8;// 设置搜索的带宽，DVBTunerInfo中有存储支持的带宽
				// dvbTunerInfo.tunerType = DVBTunerInfo.TUNER_TYPE_DVBC;// 设置搜索的tuner类型，DVBTunerInfo中有存储支持的tuner类型
				ICast.startManualScan(dvbTunerInfo);
			}
		});
	}

	private LinearLayout createSelectorLayout() {
		LinearLayout layout = new LinearLayout(this);
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.topMargin = -10;
		layout.setLayoutParams(params);
		layout.setOrientation(LinearLayout.HORIZONTAL);
		ctrlBar2.addView(layout);
		return layout;
	}

	private int modulation;
	private int bandWidth;
	private int tunerType;

	private void addSelectorButton(final LinearLayout layout, final String flag, String text, final int value,
			boolean isChecked) {
		Button button = new Button(this);
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, 60);
		params.setMargins(0, 0, -10, 0);
		button.setLayoutParams(params);
		button.setGravity(Gravity.CENTER);
		button.setText(text);
		button.setTextSize(8);
		if (isChecked) {
			button.setTextColor(0xff00A2E8);
		} else {
			button.setTextColor(0xffffffff);
		}
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				for (int i = 1; i < layout.getChildCount(); i++) {
					((Button) layout.getChildAt(i)).setTextColor(0xffffffff);
				}
				((Button) v).setTextColor(0xff00A2E8);
				if (flag.equals("modulation")) {
					modulation = value;
				} else if (flag.equals("bandWidth")) {
					bandWidth = value;
				} else if (flag.equals("tunerType")) {
					tunerType = value;
				}
			}
		});
		layout.addView(button);
	}

	/**
	 * 输出打印信息
	 */
	public static void log(String log) {
		TextView logTextView = new TextView(activity);
		logTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		logTextView.setText(log);
		logTextView.setGravity(Gravity.RIGHT);
		logTextView.setTextSize(12);
		logList.addView(logTextView);
		new Handler().post(new Runnable() {
			@Override
			public void run() {
				logScroll.fullScroll(ScrollView.FOCUS_DOWN);
			}
		});
	}

	/**************************************** 播放器 ****************************************/

	private SurfaceView surView;

	private void playerInit() {
		surView = (SurfaceView) findViewById(R.id.livevideo_surface_view);
		Interlayer.setSurfaceView(surView);
	}

	/**************************************** 频道列表 ****************************************/

	private static ListView channelList;

	private void channelInit() {
		channelList = (ListView) findViewById(R.id.channellist);
	}

	/**
	 * 创建频道列表
	 */
	public static void createChannelList() {
		ArrayList<String> dataList = new ArrayList<String>();
		DVBServiceInfo[] DVBServiceInfo = ICast.getChannels();
		if (DVBServiceInfo != null && DVBServiceInfo.length > 0) {
			for (int i = 0; i < DVBServiceInfo.length; i++) {
				DVBServiceInfo info = DVBServiceInfo[i];
				String channelName = info.serviceName;
				dataList.add(channelName);
			}
			channelList.setAdapter(new ArrayAdapter<String>(activity, R.layout.item_list2, dataList));
			channelList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					ICast.startPlay(arg2);
				}
			});
		} else {
			LogCat.log("创建频道列表失败：频道列表为空");
		}
	}

	/**************************************** CI/PIN 弹框 ****************************************/

	private static DialogCi dialogCi;
	private static DialogPin dialogPin;

	public static void showCiDialog() {
		if (dialogCi != null) {
			dialogCi.refresh();
		} else {
			dialogCi = new DialogCi(activity);
			dialogCi.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialogCi.show();
			dialogCi.initView();
		}
	}

	public static void closeCiDialog() {
		if (dialogCi != null) {
			dialogCi.dismiss();
			dialogCi = null;
		}
	}

	public static void showPinDialog() {
		closePinDialog();
		dialogPin = new DialogPin(activity);
		dialogPin.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialogPin.show();
		dialogPin.initView();
	}

	public static void closePinDialog() {
		if (dialogPin != null) {
			dialogPin.dismiss();
			dialogPin = null;
		}
	}
}
